package com.frank.oj.service.admin.training.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.frank.model.entity.training.TrainingCategory;
import com.frank.oj.common.exception.StatusFailException;
import com.frank.oj.service.admin.training.AdminTrainingCategoryService;
import com.frank.oj.service.entity.training.TrainingCategoryEntityService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author frank
 * @Date 2024/4/8
 */
@Service
public class AdminTrainingCategoryServiceImpl implements AdminTrainingCategoryService {
    @Resource
    private TrainingCategoryEntityService trainingCategoryEntityService;

    @Override
    public TrainingCategory addTrainingCategory(TrainingCategory trainingCategory) throws StatusFailException {
        LambdaQueryWrapper<TrainingCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(trainingCategory.getGid() != null, TrainingCategory::getGid, trainingCategory.getGid())
                .eq(TrainingCategory::getName, trainingCategory.getName());
        TrainingCategory old = trainingCategoryEntityService.getOne(queryWrapper);

        if (old != null) {
            throw new StatusFailException("该分类已存在");
        }
        boolean saved = trainingCategoryEntityService.save(trainingCategory);
        if (!saved) {
            throw new StatusFailException("添加失败");
        }
        return trainingCategory;
    }

    @Override
    public void updateTrainingCategory(TrainingCategory trainingCategory) throws StatusFailException {
        boolean updated = trainingCategoryEntityService.updateById(trainingCategory);
        if (!updated) {
            throw new StatusFailException("更新失败");
        }
    }

    @Override
    public void deleteTrainingCategory(Long cid) throws StatusFailException {
        boolean removed = trainingCategoryEntityService.removeById(cid);
        if (!removed) {
            throw new StatusFailException("删除失败");
        }
    }
}
